package com.qiuyuliantu.base.service.impl;

import java.util.Date;
import java.util.List;

import com.qiuyuliantu.common.core.domain.entity.SysUser;
import com.qiuyuliantu.common.exception.ServiceException;
import com.qiuyuliantu.common.utils.DateUtils;
import com.qiuyuliantu.common.utils.SecurityUtils;
import com.qiuyuliantu.common.utils.StringUtils;
import com.qiuyuliantu.common.utils.bean.BeanValidators;
import com.qiuyuliantu.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qiuyuliantu.base.mapper.QiuAccountingRecordMapper;
import com.qiuyuliantu.base.domain.QiuAccountingRecord;
import com.qiuyuliantu.base.service.IQiuAccountingRecordService;

import javax.validation.Validator;

/**
 * 记账记录Service业务层处理
 *
 * @author lmx
 * @date 2025-07-28
 */
@Service
public class QiuAccountingRecordServiceImpl implements IQiuAccountingRecordService
{
    @Autowired
    private QiuAccountingRecordMapper qiuAccountingRecordMapper;

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    protected Validator validator;

    /**
     * 查询记账记录
     *
     * @param id 记账记录主键
     * @return 记账记录
     */
    @Override
    public QiuAccountingRecord selectQiuAccountingRecordById(Long id)
    {
        return qiuAccountingRecordMapper.selectQiuAccountingRecordById(id);
    }

    /**
     * 查询记账记录列表
     *
     * @param qiuAccountingRecord 记账记录
     * @return 记账记录
     */
    @Override
    public List<QiuAccountingRecord> selectQiuAccountingRecordList(QiuAccountingRecord qiuAccountingRecord)
    {
        return qiuAccountingRecordMapper.selectQiuAccountingRecordList(qiuAccountingRecord);
    }

    /**
     * 新增记账记录
     *
     * @param qiuAccountingRecord 记账记录
     * @return 结果
     */
    @Override
    public int insertQiuAccountingRecord(QiuAccountingRecord qiuAccountingRecord)
    {
        qiuAccountingRecord.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        qiuAccountingRecord.setCreateTime(DateUtils.getNowDate());
        // 当前用户信息
        qiuAccountingRecord.setUserId(SecurityUtils.getUserId());
        qiuAccountingRecord.setDeptId(SecurityUtils.getDeptId());
        return qiuAccountingRecordMapper.insertQiuAccountingRecord(qiuAccountingRecord);
    }

    /**
     * 修改记账记录
     *
     * @param qiuAccountingRecord 记账记录
     * @return 结果
     */
    @Override
    public int updateQiuAccountingRecord(QiuAccountingRecord qiuAccountingRecord)
    {
        qiuAccountingRecord.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        qiuAccountingRecord.setUpdateTime(DateUtils.getNowDate());
        return qiuAccountingRecordMapper.updateQiuAccountingRecord(qiuAccountingRecord);
    }

    /**
     * 批量删除记账记录
     *
     * @param ids 需要删除的记账记录主键
     * @return 结果
     */
    @Override
    public int deleteQiuAccountingRecordByIds(Long[] ids)
    {
        return qiuAccountingRecordMapper.deleteQiuAccountingRecordByIds(ids);
    }

    /**
     * 删除记账记录信息
     *
     * @param id 记账记录主键
     * @return 结果
     */
    @Override
    public int deleteQiuAccountingRecordById(Long id)
    {
        return qiuAccountingRecordMapper.deleteQiuAccountingRecordById(id);
    }


    /**
     * 导入用户数据
     *
     * @param recordList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importRecord(List<QiuAccountingRecord> recordList, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(recordList) || recordList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (QiuAccountingRecord record : recordList)
        {
            try
            {
                // 验证是否存在这个用户
                QiuAccountingRecord r = qiuAccountingRecordMapper.selectRecordByRecordr(record);
                if (StringUtils.isNull(r))
                {
                    BeanValidators.validateWithException(validator, record);

                    record.setUserId(SecurityUtils.getUserId());
                    record.setDeptId(SecurityUtils.getDeptId());
                    record.setCreateTime(new Date());
                    record.setCreateBy(operName);
                    qiuAccountingRecordMapper.insertQiuAccountingRecord(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账单时间： " + record.getBorrowReturnTime() + "、金额： " + record.getAmount() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, record);
                    record.setUserId(SecurityUtils.getUserId());
                    record.setDeptId(SecurityUtils.getDeptId());
                    record.setUpdateBy(operName);
                    qiuAccountingRecordMapper.updateQiuAccountingRecord(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账单时间： " + record.getBorrowReturnTime() + "、金额： " + record.getAmount() +  " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、账单时间： " + record.getBorrowReturnTime() + "、金额： " + record.getAmount() +  " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum +"、账单时间： " + record.getBorrowReturnTime() + "、金额： " + record.getAmount() +" 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
